import React, { FunctionComponent, useState } from 'react';
import styles from './index.less';
import { IFoodProps, ISkuProps } from '../sell';
import { Button, Stepper } from 'react-vant';
import { useSelector, useDispatch } from 'umi';
import { IGlobalState, ICartProps } from '@/models/global';

export interface IFoodCardProps {
    /** 商品信息 */
    foodDetail: IFoodProps | null;
    hideCartPop: () => void;
    syncGoodsByDva: () => void;
}

interface IFoodSkuProps extends ISkuProps {
    values: Array<{ label: string; value: string, checked?: boolean; }>;
}

interface IFoodParamsProps extends IFoodProps {
    /** 要买的数量 */
    buy_numbers: number
    /** sku */
    sku?: Array<IFoodSkuProps>;
}

/** 商品购买卡片组件 */
const FoodCard: FunctionComponent<IFoodCardProps> = ({ foodDetail, hideCartPop, syncGoodsByDva }) => {

    const globalState = useSelector((state: { globalState: IGlobalState }) => state.globalState);
    const dispatch = useDispatch()

    const [foodParams, setFoodParams] = useState<IFoodParamsProps | null>(foodDetail ? {
        ...foodDetail,
        buy_numbers: 1,
        sku: foodDetail.sku ? foodDetail.sku.map((item) => ({
            ...item,
            values: item.values.map((op, i) => ({ ...op, checked: i === 0 ? true : false }))
        })) : []
    } : null);


    // 切换sku
    const checkoutSku = (index: number, num: number) => {
        if (foodParams) {
            let { sku } = foodParams;
            sku = sku?.map((item, i) => {
                if (index == i) {
                    item.values = item.values.map((itemize, j) => ({
                        ...itemize,
                        checked: j === num ? true : false
                    }))
                }
                return item;
            })
            setFoodParams({
                ...foodParams,
                sku
            })
        }
    }


    /** 获取当前选择的sku的ids */
    const getCheckedSkuIds = () => {
        let skuSpliceId = '';
        foodParams?.sku?.forEach(item => {
            item.values.forEach(skuitem => {
                if (skuitem.checked) skuSpliceId += (skuitem.value + ',')
            })
        })
        skuSpliceId = skuSpliceId.slice(0, skuSpliceId.length - 1);
        skuSpliceId = skuSpliceId ? String(foodParams?.foodId) + '|' + skuSpliceId : String(foodParams?.foodId)
        return skuSpliceId
    }

    /** 加入购物车 */
    const addShoppingcars = () => {
        // 1.隐藏遮罩层 2.调接口更新用户购物车数据 3.http响应后改边sell父组件里的goods数据，同步渲染
        dispatch({
            type: 'globalState/addSkuFoodToCart', payload: {
                ...foodParams,
                skuSpliceId: getCheckedSkuIds()
            }
        })
        hideCartPop()
        syncGoodsByDva()
    }

    /** sku对应的价格 */
    const getPrice = () => {
        if (foodParams) {
            let price = foodParams.price;
            if (foodParams.sku && foodParams.skuMap) {
                const { skuMap } = foodParams
                const ids = getCheckedSkuIds();
                skuMap.forEach(item => {
                    if (foodParams.foodId + '|' + item.ids === ids) {
                        price = item.price
                    }
                })
            }
            return price
        }
    }

    /** 当前选中规格 */
    const getSkuLabel = () => {
        let labels = ''
        if (foodParams && foodParams.sku) {
            foodParams.sku.forEach(item => {
                item.values.forEach(val => {
                    if (val.checked) labels += (val.label + ',')
                })
            })
        }
        return labels.slice(0, labels.length - 1)
    }

    return foodParams ?
        (<div className={styles.foodcard}>
            <div className={styles.foodcard_top}>
                <img className={styles.foodcard_img} src={foodParams.image}></img>
                <div className={styles.foodcard_wrapper}>
                    <div className={styles.foodcard_title}>{foodParams.name}</div>
                    <div className={styles.foodcard_info}>{foodParams.info}</div>
                    <div className={styles.foodcard_sku}>
                        {
                            foodParams.sku?.map((item, index) => (
                                <div className={styles.foodcard_sku_content} key={'sku' + index}>
                                    <span>{item.title}</span>
                                    <div className={styles.foodcard_sku_content_skumenu}>
                                        {
                                            item.values.map((skuitem, num) => (
                                                <span key={'skuitem' + num}
                                                    onClick={() => checkoutSku(index, num)}
                                                    className={`${styles.foodcard_sku_content_skumenu_item} ${skuitem.checked ? styles.foodcard_sku_content_skumenu_item_checked : ''}`}
                                                >
                                                    {skuitem.label}</span>
                                            ))
                                        }
                                    </div>
                                </div>
                            ))
                        }
                    </div>
                </div>
            </div>
            <div className={styles.foodcard_down}>
                <div className={styles.foodcard_down_price}>
                    <div className={styles.foodcard_down_price_info}>
                        ￥{getPrice()}
                        <div className={styles.foodcard_down_price_info_sku}>{getSkuLabel()}</div>
                    </div>
                    <Stepper
                        value={foodParams.buy_numbers}
                        theme="round" buttonSize="22"
                        disableInput
                        onPlus={() => { setFoodParams({ ...foodParams, buy_numbers: foodParams.buy_numbers + 1 }) }}
                        onMinus={() => { setFoodParams({ ...foodParams, buy_numbers: foodParams.buy_numbers - 1 }) }}
                    />
                </div>
                <Button type="primary" block round onClick={addShoppingcars}>加入购物车</Button>
            </div>
        </div>) :
        <div></div>
}

export default FoodCard